package org.example;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.example.config.MysqlExecute;
import org.example.execute.*;
import org.example.service.GenerateCode;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

@Mojo(name = "generate-mysql")
public class GenerateMysql extends AbstractMojo {


    @Parameter(name = "configurationFile",defaultValue = "src/main/resources/generatorConfig.yml", readonly = true)
    private File configurationFile;

    private List<GenerateCode> generateCodeList = new ArrayList();

    public void init() {
        generateCodeList.add(new Entity());
        generateCodeList.add(new Mapper());
        generateCodeList.add(new MapperXml());
        generateCodeList.add(new Service());
        generateCodeList.add(new ServiceImpl());
        generateCodeList.add(new Controller());
    }

    @Override
    public void execute() {
        init();
        try {
            Properties properties = new Properties();
            properties.load(new FileInputStream(configurationFile.getPath()));
            String[] entitys = properties.getProperty("generator.list").split(",");
            MysqlExecute mysqlExecute = new MysqlExecute(properties);
            List<String> tables = mysqlExecute.getTables();
            tables.retainAll(Arrays.asList(entitys));
            getLog().info("tables:" + tables);
            for (String table : tables) {
                generateCodeList.stream().forEach(generateCode -> generateCode.execute(getLog(), table, mysqlExecute.getFields(table), properties));
            }
            mysqlExecute.close();
        } catch (ClassNotFoundException | SQLException | IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
